import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { getBanners, getHotReccomend, getNewAlbum } from '../service/recommend'

// 发送网络请求，存储到store中
// 获取轮播图
export const fetchBannerDataAction = createAsyncThunk(
  'banners',
  async (arg, { dispatch }) => {
    const res = await getBanners()
    // return res.banners
    dispatch(changeBannersAction(res.banners))
  }
)

// 获取热门推荐数据
export const fetchRecommendDataAction = createAsyncThunk(
  'hotRecommend',
  async (arg, { dispatch }) => {
    const res = await getHotReccomend(8)
    // return res.banners
    dispatch(changeHotRecommendAction(res.result))
  }
)

// 获取新碟上架数据
export const fetchNewAlbgumAction = createAsyncThunk(
  'newAlbum',
  async (arg, { dispatch }) => {
    const res = await getNewAlbum()
    // return res.banners
    dispatch(changeNewAlbumAction(res.albums))
  }
)

interface IRecommendState {
  banners: any[]
  hotRecommends: any[]
  newAlbum: any[]
}

const initialState: IRecommendState = {
  banners: [],
  hotRecommends: [],
  newAlbum: []
}

const recommendSlice = createSlice({
  name: 'recommend',
  initialState,
  reducers: {
    changeBannersAction(state, action) {
      state.banners = action.payload
    },
    changeHotRecommendAction(state, action) {
      state.hotRecommends = action.payload
    },
    changeNewAlbumAction(state, action) {
      state.newAlbum = action.payload
    }
  }
})

export const {
  changeBannersAction,
  changeHotRecommendAction,
  changeNewAlbumAction
} = recommendSlice.actions

export default recommendSlice.reducer
